/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.user.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;

/**
 * The utility class provides methods for manipulating elements.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class Elements {

  /**
   * Checks whether the given element has a class name.
   * 
   * @param name the class name
   * @param e the element to check
   * @return true for matching, false for otherwise
   */
  public static boolean hasClass(String name, Element e) {
    String className = e.getClassName();
    int idx = className.indexOf(name);

    // Calculate matching index.
    while (idx != -1) {
      if (idx == 0 || className.charAt(idx - 1) == ' ') {
        int last = idx + name.length();
        int lastPos = className.length();
        if ((last == lastPos) || ((last < lastPos) && (className.charAt(last) == ' '))) {
          return true;
        }
      }
      idx = className.indexOf(name, idx + 1);
    }

    return false;
  }

  /**
   * Finds all the elements that has the given class name.
   * 
   * @param context the context to traverse
   * @param className the class name
   * @return the matched elements
   */
  public static List<Element> findByClass(Element context, String className) {
    List<Element> result = new ArrayList<Element>();
    for (int i = 0; i < context.getChildCount(); i++) {
      Node node = context.getChildNodes().getItem(i);
      if (Element.is(node)) {
        Element e = node.cast();
        if (Elements.hasClass(className, e)) {
          result.add(e);
        }
      }
    }
    return result;
  }

  /**
   * Gets the unique element that has the given class name.
   * 
   * @param context the context to travse
   * @param className the class name
   * @return the matched element
   */
  public static Element getByClass(Element context, String className) {
    for (int i = 0; i < context.getChildCount(); i++) {
      Node node = context.getChildNodes().getItem(i);
      if (Element.is(node)) {
        Element e = node.cast();
        if (Elements.hasClass(className, e)) {
          return e;
        }
      }
    }
    return null;
  }

}
